package top.birdhk.TestAPI.transorm;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import top.birdhk.TestAPI.beans.SensorReading;

public class Transform_Reduce {

    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> inputSream = env.readTextFile("E:\\flink\\wordcount\\src\\main\\resources\\sensor.txt");

        env.setParallelism(1);

        SingleOutputStreamOperator<SensorReading> dataStream = inputSream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });


        // 分组
        KeyedStream<SensorReading, String> keyedStream = dataStream.keyBy(SensorReading::getId);

        // reduce聚合，取最大的温度值，当前最新的时间戳
        SingleOutputStreamOperator<SensorReading> reduce = keyedStream.reduce(new ReduceFunction<SensorReading>() {
            @Override
            public SensorReading reduce(SensorReading sensorReading, SensorReading t1) throws Exception {
                return new SensorReading(sensorReading.getId(), t1.getTimestamp(), Math.max(sensorReading.getTemperature(), t1.getTemperature()));
            }
        });

        // 滚动聚合,取当前的最大值
        SingleOutputStreamOperator<SensorReading> max = keyedStream.maxBy("temperature");

        reduce.print();

        env.execute();


    }


}
